// local setup
$(function local_setup () {
    var c_server_host = $('#server-host');
    $(window).on ('resize', function () {
        var toolbar = $('.tool-bar'), top = toolbar.offset ().top + toolbar.height (), H = $(window).height ();
        $('.server-list, .root-container').css ({height:H-top});
    }).trigger ('resize');

    $('#btn-ok').on ('click', function () {
        if (!$(this).hasClass ('disabled')) {
            var current = $('.server-list>li.selected');
            if (current.length) {
                var serverName = current.attr ('data-server-name'),
                    server     = localCache.servers [serverName];

                if (server && is_dirty ()) {
                    // server.name           = serverName;
                    server.host           = c_server_host.val ();
                    server.manage_port    = $('#manage-port').val ();
                    server.connector_port = $('#connector-port').val ();

                    try {
                        var o = bridge.require ('save', JSON.stringify (server));
                        if (o) {
                            delete server ['editing'];
                            current.removeAttr ('data-editing');
                            do_cancel ();
                            $.Alert.success (RS(R, 'server-manager.messages.save-ok'));
                        } else {
                            $.Alert.error (RS(R, 'server-manager.messages.save-fail'));
                        }
                    } catch (ex) {
                        console.error (ex);
                    }
                }
            }
        }
    });

    $('#btn-remove').on ('click', function () {
        try {
            var current = $('.server-list>li.selected');
            if (current.length) {
                var serverName = current.attr ('data-server-name');
                $.Alert.warn (RS(R, 'server-manager.messages.confirm-delete', {name:serverName}), 'after-close', function () {
                    try {
                        var server = localCache.servers [serverName], code;
                        if ('editing' in server && server.editing === true) {
                            do_remove (current, serverName);
                        } else {
                            code = bridge.require ('remove', serverName);
                            if (code == 0) {
                                do_remove (current, serverName);
                            } else if (code == 1) {
                                $.Alert.error (RS(R, 'server-manager.messages.server-in-use', {name:serverName}));
                            } else {
                                $.Alert.error (RS(R, 'server-manager.messages.delete-fail'));
                            }
                        }
                    } catch (ex) {
                        console.error (ex);
                    }
                });
            }
        } catch (ex) {
            console.error (ex);
        }
    });

    $('#btn-cancel').on ('click', function () {
        if ($(this).hasClass ('disabled')) {
            return;
        }

        var selected = $('.server-list>li.selected'), serverName, server;
        if (selected.length) {
            serverName = selected.attr ('data-server-name');
            server = localCache.servers [serverName];
            if (server && server.editing) {
                // new-created server, just remove it
                $('#btn-remove').trigger ('click');
            } else {
                if (is_dirty ()) {
                    $.Alert.warn (RS (R, 'server-manager.messages.prompt-cancel'), do_cancel);
                } else {
                    do_cancel ();
                }
            }
        }
    });

    $('#btn-create').on ('click', function () {
        var self = $(this), selected, server, serverName;
        if (self.hasClass ('disabled')) {
            return;
        }
        selected = $('.server-list>li.selected');
        if (selected.length) {
            serverName = selected.attr ('data-server-name');
            server = localCache.servers [serverName];
            if (server && server.editing) {
                // new-created server
                $.Alert.warn (RS (R, 'server-manager.messages.prompt-cancel'), 'after-close', function () {
                    selected.remove ();
                    reset_form ();
                    delete localCache.servers [serverName];

                    do_create (selected);
                });
            } else {
                if (is_dirty ()) {
                    $.Alert.warn (RS (R, 'server-manager.messages.prompt-cancel'), 'after-close', function () {
                        do_create (selected);
                    });
                }
            }
        } else {
            // no server is selected, create new one.
            do_create (selected);
        }
    });

    function do_create (selected) {
        try {
            var serverList = $('.server-list'), li = $('<li class="selected"/>').appendTo (serverList).focus ();
            selected.removeClass ('selected');
            serverList.animate({scrollTop: li.offset().top}, 500);
            $('<input type="text" class="form-control" id="server-name" value="Unnamed Server"/>')
                .on ('blur', on_server_name_changed).on ('keydown', function (e) {
                    if (e.keyCode === 13) {
                        $(this).trigger ('blur');
                    } else if (e.keyCode === 27) { // escape
                        this.value = '';
                        do_cancel ();
                    }
                }).appendTo (li).select ().focus ();
            $('.maskable').removeAttr ('readonly');
            reset_form ();
        } catch (ex) {
            console.error (ex);
        }
    }

    function do_remove (current, serverName) {
        $('#btn-ok, #btn-cancel').addClass ('disabled');
        $.Alert.success (RS(R, 'server-manager.messages.delete-ok'));
        do_cancel ();
        current.remove ();
        delete localCache.servers [serverName];
    }

    $('.maskable').on ('keyup', check_button_state);
    $('.number-field').on ('keydown', port_checker);
});
// end of local setup

// javafx-javascript stub
function on_page_load (data) {
    if (typeof data === 'string') {
        data = eval ('(' + data + ')');
    }

    var servers, i, v;
    if ('servers' in data) {
        servers = data ['servers'];
        localCache.servers = {};
        for (i = 0; i < servers.length; i ++) {
            v = servers [i];
            localCache.servers [v.name] = v;

            append_server (v);
        }
    }
}

function on_close () { 
    var current = $('.server-list>li.selected');
    if (current.length && is_dirty ()) {
        $.Alert.warn (RS(R, 'server-manager.messages.confirm-close'), function () {
            bridge.require ('force-close');
        });
        return false;
    }
    return true;
}

function update_ui () {
    var locale = window.LOCALE || 'en_US';
    var res = window.R[locale]['server-manager'].labels, k, v;
    for (k in res) if (res.hasOwnProperty (k)) {
        v = res[k];
        if (k.startsWith ('lbl-')) {
            // labels
            $('#' + k).text (v);
        } else if (k.startsWith ('btn-')) {
            // buttons
            $('.' + k).attr ('title', v)
        }
    }
}
// end of javafx-javascript stub

// local varibles and functions
var localCache = {};

function do_cancel () {
    reset_form ();
    $('.maskable').attr ('readonly', 'readonly');
    $('#btn-ok, #btn-cancel').attr ('disabled', 'disabled').addClass ('disabled');
    $('#server-name').val ('').remove ();// .appendTo ($('#hidden-panel'));
    $('.server-list>li[data-editing=true]').remove ();
    $('.server-list>li').removeClass ('selected');
}

function append_server (server) {
    if (!server) {
        return;
    }

    var serverList = $('.server-list'), 
        li = $('<li/>').attr ('data-server-name', server.name)
            .on ('click', on_server_clicked).appendTo (serverList);
    $('<a/>').text (server.name).appendTo (li);
}

function on_server_clicked () {
    var selected = $('.server-list>li.selected'), self = $(this);
    if (selected.attr ('data-server-name') === self.attr ('data-server-name')) {
        // the same item, nothing to do, but focus host field
        do_server_clicked.apply (self, [selected]);
        return;
    }

    // var editing = $('.server-list>li[data-editing=true]');
    if (selected.length && is_dirty ()) {
        // a server under editing, show alarm message
        $.Alert.options ['warn'] = {onclose:function () {
            $('#server-host').focus ();
            delete $.Alert.options ['warn'];
        }}
        $.Alert.warn (RS (R, 'server-manager.messages.prompt-cancel'), 'after-close', function () {
            do_server_clicked.apply (self, [selected]);
        });
    } else {
        do_server_clicked.apply (self, [selected]);
    }
}

function do_server_clicked (selected) {
    try {
        selected.removeClass ('selected');
        var self = $(this).addClass ('selected'), server = localCache.servers [self.attr ('data-server-name')];
        if (server) {
            $('.maskable').removeAttr ('readonly');
            $('#server-host').val (server.host).focus ();
            $('#manage-port').val (server.manage_port);
            $('#connector-port').val (server.connector_port);

            $('.error-message').text ('');
        }
        $('#btn-remove, #btn-cancel, #btn-ok').removeClass ('disabled').removeAttr ('disabled');
    } catch (ex) {
        console.error (ex);
    }
}

function on_server_name_changed () { 
    var self, li;
    if ('servers' in localCache && this.value in localCache.servers) {
        $.Alert.options ['error'] = {
            onclose : function (e) {
                $('#server-name').select ().focus ();
                delete $.Alert.options ['error'];   // self-killing
            }
        };
        $.Alert.error (RS (R, 'server-manager.messages.error-name-exists', {name:this.value}));
        return;
    }
    self = $(this);
    li = self.closest ('li').attr ({'data-editing':true, 'data-server-name':this.value}).focus ().on ('click', on_server_clicked);
    self.remove ();
    $('<a/>').text (self.val ()).appendTo (li);

    reset_form ();
    $('.server-list>li.selected').removeClass ('selected');
    li.addClass('selected');
    $('#server-host').focus ();

    if (!('servers' in localCache)) {
        localCache.servers = {};
    }
    localCache.servers[this.value] = {name:this.value, host:'', manage_port:'', connector_port:'', editing:true};
}

function reset_form () {
    $('.error-message').text ('');
    $('.maskable').val ('');
    $('#btn-remove, #btn-ok, #btn-cancel').addClass ('disabled').prop ('disabled', false);
}

function check_button_state () {
    var controls = $('.form-control'), i;
    for (i = 0; i < controls.length; i ++) {
        if (controls [i].value === '') {
            $('#btn-ok').attr ('disabled', 'disabled').addClass ('disabled');
            if ($('.server-list>li[data-editing=true]').length) {
                // $('#btn-cancel').removeAttr ('disabled').removeClass ('disabled');
                $('.server-list>li.selected').attr ('data-editing', true);
            }
            return;
        }
    }
    $('#btn-ok').removeAttr ('disabled').removeClass ('disabled');
    $('.server-list>li.selected').removeAttr ('data-editing');
}

function is_dirty () {
    var current = $('.server-list>li.selected');
    if (!current.length) {
        return false;
    }

    var serverName    = current.attr ('data-server-name'),
        server        = localCache.servers [serverName],
        serverHost    = $('#server-host').val (),
        managePort    = $('#manage-port').val (),
        connectorPort = $('#connector-port').val ();

    return server.host !== serverHost       ||
           server.manage_port != managePort ||
           server.connector_port != connectorPort;
}
// end of local varibles and functions